package com.zby.simulationHibernate.util.factory;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created By zby on 15:43 2019/1/23
 */
public class SqlSessionFactory implements SessionFactory {

    /**
     * 连接池
     */
    private static List<Connection> connections;

    /**
     * 连接对象
     *
     * @return
     */
    private static Connect connect = new Connect();

    /**
     * Created By zby on 16:10 2019/3/17
     * 获取容器的对象，如果是关闭session，则将连接对象放回到容器中
     * 如果是开启session，则从容器中删除该连接对象
     */
    protected static List<Connection> getConnections() {
        return connections;
    }


    //静态代码块，初始化常量池
    static {
        connections = new ArrayList<>();
        Connection connection;
        for (int i = 0; i < Connect.minPoolSize; i++) {
            connection = connect.createConnect();
            connections.add(connection);
        }
    }

    @Override
    public Session openSession() {
        return getSession(false);
    }

    @Override
    public Session getCurrentSession() {
        return getSession(true);
    }

    /**
     * 获取session
     *
     * @param autoCommit 是否自动提交事务
     * @return
     */
    private Session getSession(boolean autoCommit) {
        //【1】判断连接池有可用的连接对象
        boolean hasNoValidConn = hasValidConnction();
        //【2】没有可用的连接池，使用最大的连接池
        if (!hasNoValidConn) {
            for (int i = 0; i < (Connect.maxPoolSize - Connect.minPoolSize); i++) {
                connections.add(connect.createConnect());
            }
        }
        //【3】有可用的连接
        for (Iterator iterator = connections.iterator(); iterator.hasNext(); ) {
            Connection connection = null;
            try {
                connection = (Connection) iterator.next();
                connection.setAutoCommit(autoCommit);
                Session session = new Session(connection);
                iterator.remove();
                return session;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Created By zby on 21:50 2019/1/23
     * 当我们没开启一个连接，连接池的数目减少1，直到连接池的数量为0
     */
    private boolean hasValidConnction() {
        return null != connections && connections.size() != 0;
    }
}
